package com.main.test;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpHexClient {
    private static final String SERVER_HOST = "192.168.0.178";
    private static final int SERVER_PORT = 4001;
    private static final byte type = -119;
    private static final byte typeResult = 10;//表示成功

    private static final byte typeSelectResult = 16;

    private static  Socket socket =null;
    private static OutputStream outputStream = null;
    private static InputStream inputStream = null;
    public static void main(String[] args) {
        try {
/*

            // 要发送的十六进制字符串
            String hexDataToSend = "A0 04 01 89 01 D1";
            // 去除空格
            hexDataToSend = hexDataToSend.replace(" ", "");
            // 将十六进制字符串转换为字节数组
            byte[] byteData = hexStringToByteArray(hexDataToSend);
*/socket = new Socket(SERVER_HOST, SERVER_PORT);
       outputStream = socket.getOutputStream();
       inputStream = socket.getInputStream();
            Scanner scanner = new Scanner(System.in);
           // scanner.nextLine();
            System.out.println("下发盘库指令：A004018901");
           String str =scanner.nextLine();
           // byte[] byteData = CheckByteCRC.checkCRC("A004018901");

            byte[] byteData = CheckByteCRC.checkCRC(str);
            //得到校验后的值并且发送
            // 发送字节数组到服务器
            outputStream.write(byteData);
            System.out.println("已发送十六进制数据: " + str);

            // 持续接收服务器的数据
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 提取实际接收到的数据
                byte[] receivedData = new byte[bytesRead];
                System.arraycopy(buffer, 0, receivedData, 0, bytesRead);
                if (receivedData[1]!=typeResult) {
                    String ecp = DataUtil.getEcp(receivedData);
                    System.out.println("收到服务器返回并解析到的EPC为: " + ecp);
                }
                //表示成功
                if (receivedData[1]==typeResult){
                    break;
                }
            }
            System.out.println("接收完成");
            System.out.println("看看outputStream对象还在不在："+outputStream);
            //  todo 先选定epc
            System.out.println("选定epc");
            String selectEPCStr =scanner.nextLine();
            //将数字字母转为byte
            byte[] selectEPC = DataUtil.convertTo12Byte(selectEPCStr);
            byte[] selectCmd = DataUtil.getWselectCmd(selectEPC);
            System.out.println("下发选定指令没有校验的值："+byteArrayToHexString(selectCmd));
            //进行crc验证
            byte[] selectRfidWriteCmd= CheckByteCRC.checkCRC(selectCmd);
            System.out.println("下发给设备选定的的十六进制内容："+byteArrayToHexString(selectRfidWriteCmd));
            //下发指令
            outputStream.write(selectRfidWriteCmd);
            // 持续接收服务器的数据
            byte[] buffer1 = new byte[1024];
            int bytesRead1;
            while ((bytesRead1 = inputStream.read(buffer1)) != -1) {
                // 提取实际接收到的数据
                byte[] receivedData = new byte[bytesRead1];
                System.arraycopy(buffer1, 0, receivedData, 0, bytesRead1);
                System.out.println("选定接收到的十六进制："+byteArrayToHexString(receivedData));

                System.out.println("是否成功："+receivedData[4]);
                if (receivedData[4]==typeSelectResult){
                    System.out.println("选定epc成功！！");
                    break;
                }

            }

            //再次输入修改的值
            System.out.println("输入要修改的epc的值");
            String epcStr =scanner.nextLine();
            byte[] bytes = DataUtil.convertTo12Byte(epcStr);
            byte[] writeCmd = DataUtil.getWriteCmd(bytes);
            //进行crc验证
            byte[] toRfidWriteCmd= CheckByteCRC.checkCRC(writeCmd);
            System.out.println("下发给设备的十六进制内容："+byteArrayToHexString(toRfidWriteCmd));
            //输入要改成的十六进制的字符串
            outputStream.write(toRfidWriteCmd);
            // 持续接收服务器的数据
            byte[] buffer2 = new byte[1024];
            int bytesRead2;
            while ((bytesRead2 = inputStream.read(buffer2)) != -1) {
                // 提取实际接收到的数据
                byte[] receivedData = new byte[bytesRead2];
                System.arraycopy(buffer2, 0, receivedData, 0, bytesRead2);
                System.out.println("接收到的十六进制："+byteArrayToHexString(receivedData));
                byte receivedDatum = receivedData[1];
                int count=receivedDatum;//19
                int i = count + 2 - 1 - 3;
                System.out.println("是否成功："+receivedData[i]);
               if (receivedData[i]==typeResult){
                   System.out.println("epc修改成功！！");

               }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //取高五位
    public static int getECPCount(byte len){

       // byte len = 48;

        // 右移 3 位提取高五位
        int highFiveBits = len >> 3;

        // 输出结果
        System.out.println("byte 类型变量 a 的二进制高五位对应的十进制值是: " + highFiveBits);
        return highFiveBits;
    }

    /**
     * 将十六进制字符串转换为字节数组
     * @param hex 十六进制字符串
     * @return 字节数组
     */
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    /**
     * 将字节数组转换为十六进制字符串
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    public static String byteArrayToHexString(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02X", b & 0xFF));
            result.append(" ");
        }
        return result.toString();
    }
}